import gc
import machine
import network
import webrepl
import config

def connect_wlan(ssid, password):
    sta_if = network.WLAN(network.STA_IF)
    ap_if = network.WLAN(network.AP_IF)
    sta_if.active(True)
    ap_if.active(False)

    if not sta_if.isconnected():
        print("Connecting to WLAN ({})...".format(ssid))
        sta_if.active(True)
        sta_if.connect(ssid, password)
        while not sta_if.isconnected():
            pass

    return True

def init_network():

    # Wi-Fi credentials
    SSID = "OpenWrt"
    PASSWORD = "password"

    connect_wlan(SSID, PASSWORD)
    
def ota_update():
    gc.collect()

    # Install Senko from PyPi
    #upip.install("micropython-senko")

    import senko
    OTA = senko.Senko('hwman74', 'hello3', url=config.ota_url, files=["app.py"])
    
    print('ota init')

    if OTA.update():
        print("Updated to the latest version!")
        machine.reset()
        
    print('You Have Latest version!')
        
if __name__ == "__main__":
    init_network()
#     try:
#         ota_update()
#         print('ota update success!')
#     except:
#         print('ota update fail!')
#         pass
#     
#     webrepl.start()


